package com.kanshu.ksgb.fastread.doudou.common.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import java.util.Set;

/**
 * 存储相关工具类
 * Created by wanchunyang
 */
public class StorageUtils {

    public static <T> T getPreference(Context context, String pName, String key, T defaultValue) {

        SharedPreferences sp = context.getSharedPreferences(pName, Context.MODE_PRIVATE);
        if (sp.contains(key)) {
            if (defaultValue instanceof String) {
                return (T) sp.getString(key, (String) defaultValue);
            } else if (defaultValue instanceof Long) {
                return (T) Long.valueOf(sp.getLong(key, (Long) defaultValue));
            } else if (defaultValue instanceof Integer) {
                return (T) Integer.valueOf(sp.getInt(key, (Integer) defaultValue));
            } else if (defaultValue instanceof Float) {
                return (T) Float.valueOf(sp.getFloat(key, (Float) defaultValue));
            } else if (defaultValue instanceof Boolean) {
                return (T) Boolean.valueOf(sp.getBoolean(key, (Boolean) defaultValue));
            } else {
                return defaultValue;
            }
        } else {
            return defaultValue;
        }
    }

    @SuppressWarnings("ic_unchecked")
    public static <T> T getPreference(Context context, String pName, String key, Class<T> cls) {

        if (cls.equals(String.class)) {
            return (T) getPreference(context, pName, key, "");
        } else if (cls.equals(Long.class)) {
            return (T) getPreference(context, pName, key, 0L);
        } else if (cls.equals(Integer.class)) {
            return (T) getPreference(context, pName, key, 0);
        } else if (cls.equals(Float.class)) {
            return (T) getPreference(context, pName, key, 0.0f);
        } else if (cls.equals(Boolean.class)) {
            return (T) getPreference(context, pName, key, false);
        }
        return null;
    }

    public static <T> boolean setPreference(Context context, String pName, String key, T value) {

        return setPreference(context, pName, key, value, false);
    }

    public static <T> boolean setPreference(Context context, String pName, String key, T value, boolean isAsync) {

        SharedPreferences sp = context.getSharedPreferences(pName, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sp.edit();
        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        }
        if (isAsync) {
            editor.apply();
            return true;
        }
        return editor.commit();
    }

    public static <T> boolean setPreference(Context context, String pName, String key, T value, int mode) {

        SharedPreferences sp = context.getSharedPreferences(pName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        }
        return editor.commit();
    }


    public static boolean setPreferenceStringArray(Context context, String pName, String key,
                                                   Set<String> value) {
        SharedPreferences sp = context.getSharedPreferences(pName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putStringSet(key, value);
        return editor.commit();
    }

    public static Set<String> getPreferenceStringArray(Context context, String pName, String key, Set<String> set) {

        SharedPreferences sp = context.getSharedPreferences(pName, Context.MODE_PRIVATE);
        if (sp.contains(key)) {
            return sp.getStringSet(key, set);
        } else {
            return set;
        }
    }

    /**
     * 检查表是否存在
     *
     * @param db
     * @param tableName
     * @return
     */
    public static boolean checkDbTableExist(SQLiteDatabase db, String tableName) {
        if (db == null || TextUtils.isEmpty(tableName)) {
            return false;
        }
        Cursor cursor = db.rawQuery("SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?",
                new String[]{tableName});
        return cursor == null || cursor.getCount() == 0 ? false : true;
    }

    /**
     * 删除相应表的数据
     *
     * @param db
     * @param tableName
     */
    public static void deleteTableData(SQLiteDatabase db, String tableName) {
        if (db == null) {
            return;
        }
        if (checkDbTableExist(db, tableName)) {
            StringBuilder sb = new StringBuilder();
            sb.append("delete from ").append(tableName);
            db.execSQL(sb.toString());
        }
    }

    /**
     * 删除数据库中的一张表
     *
     * @param db
     * @param tableName
     */
    public static void dropTable(SQLiteDatabase db, String tableName) {
        if (db == null) {
            return;
        }
        if (checkDbTableExist(db, tableName)) {
            StringBuilder sb = new StringBuilder();
            sb.append("drop table ").append(tableName);
            db.execSQL(sb.toString());
        }
    }

    /**
     * 检查数据库表中是否有该字段
     * @param db
     * @param tableName
     * @param columnName
     * @return
     */
    public boolean checkColumnExists(SQLiteDatabase db, String tableName
            , String columnName) {
        boolean result = false ;
        Cursor cursor = null ;
        try{
            cursor = db.rawQuery( "select * from sqlite_master where name = ? and sql like ?"
                    , new String[]{tableName , "%" + columnName + "%"} );
            result = null != cursor && cursor.moveToFirst() ;
        }catch (Exception e){
        }finally{
            if(null != cursor && !cursor.isClosed()){
                cursor.close() ;
            }
        }
        return result ;
    }
}
